<template>
  <div class="app-container">
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-video-play"
          size="mini"
          class="primary-btn"
          @click="handleBatchStart"
          v-hasPermi="['system:engine:add']"
          >批量启动</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          class="reset-btn"
          icon="el-icon-video-pause"
          size="mini"
          @click="handleBatchStop"
          v-hasPermi="['system:engine:edit']"
          >批量暂停</el-button
        >
      </el-col>
    </el-row>
    <el-table
      v-loading="loading"
      :data="engineList"
      class="com-table"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="编号" align="center" type="index" />
      <el-table-column label="采集类型" align="center" prop="collectType">
        <template slot-scope="scope">
          {{ typeMaps[scope.row.collectType] }}
        </template>
      </el-table-column>
      <el-table-column label="工作状态" align="center" prop="runningStatus">
        <template slot-scope="scope">
          <span
            v-if="scope.row.runningStatus === 'FAILED'"
            style="color: #c03639; cursor: pointer;" 
            @click="handleViewLog(scope.row)"
          >
            {{ runningStatusMaps[scope.row.runningStatus] }}
            <el-icon class="el-icon-warning-outline"></el-icon>
          </span>
          <span v-else>
            {{ runningStatusMaps[scope.row.runningStatus] }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="工作开关" align="center" prop="status">
        <template slot-scope="{ row, $index }">
          <el-switch
            v-model="row.status"
            :active-value="1"
            :inactive-value="0"
            @change="handleStatusChange(row)"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="采集平台" align="center" prop="collectPlatform" />
      <el-table-column label="最近采集时间 " align="center" prop="updateTime" />
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            @click="handleViewLog(scope.row)"
            v-hasPermi="['system:engine:edit']"
            >查看日志</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination">
      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </div>

    <!-- 添加或修改采集引擎对话框 -->
    <el-dialog title="引擎日志" :visible.sync="open" width="800px" append-to-body @close="handleClose">
      <div class="log-container"  v-infinite-scroll="load" :infinite-scroll-distance="100">
        <div class="log-item" v-for="(item, index) in logArray" :key="index">
          <template  v-if="index < showIndex">
            {{ item }}
          </template>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listEngine,
  delEngine,
  startEngine,
  stopEngine,
  batchStartEngine,
  batchStopEngine,
} from "@/api/system/engine";
import { getToken } from "@/utils/auth";
export default {
  name: "Engine",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      // 采集引擎表格数据
      engineList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {},
      typeMaps: {
        TEXT: "文本",
        IMAGE: "图片",
        VIDEO: "视频",
      },
      runningStatusMaps: {
        STOPPED: "已停用",
        FAILED: "异常",
        RUNNING: "正常",
      },
      logArray: [],
      socket: null,
      interval: null,
      timeout: null,
      showIndex: 20
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询采集引擎列表 */
    getList() {
      this.loading = true;
      listEngine(this.queryParams)
        .then((response) => {
          this.engineList = response.rows || [];
          this.total = response.total || 0;
        })
        .finally(() => {
          this.loading = false;
        });
    },
    // 关闭
    handleClose() {
      this.socket.close(1000, "Normal Closure");
      clearInterval(this.interval)
      clearTimeout(this.timeout)
      this.socket = null;
    },
    // 切换工作状态 0-关闭, 1-开启
    handleStatusChange(row) {
      console.log(row)
      if(row.status === 1) {
        startEngine({ id: row.id }).then((response) => {
          this.$modal.msgSuccess("启动成功");
        }).finally(() => {
          this.queryParams.pageNum = 1;
          this.getList();
        })
      } else {
        stopEngine({ id: row.id }).then((response) => {
          this.$modal.msgSuccess("停止成功");
        }).finally(() => {
          this.queryParams.pageNum = 1;
          this.getList();
        })
      }
    },
    // 批量启动
    handleBatchStart() {
      if (this.ids.length === 0) {
        this.$modal.msgWarning("请选择需要启动的采集引擎");
        return;
      }
      batchStartEngine({ ids: this.ids }).then((response) => {
        this.$modal.msgSuccess("启动成功");
        this.queryParams.pageNum = 1;
        this.getList();
      });
    },
    // 批量暂停
    handleBatchStop() {
      if (this.ids.length === 0) {
        this.$modal.msgWarning("请选择需要暂停的采集引擎");
        return;
      }
      batchStopEngine({ ids: this.ids }).then((response) => {
        this.$modal.msgSuccess("停止成功");
        this.getList();
      });
    },
    // 查看日志
    handleViewLog(row) {
      this.logArray = [];
      this.connect(row.id)
      this.open = true;
      this.showIndex = 20;
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    // socket链接
    connect(engineId) {
      let _this = this;
      let socket;
      let reconnectInterval = 5000; // 重连间隔时间
      let heartbeatInterval = 30000; // 心跳间隔时间
      let missedHeartbeats = 0;
      const maxMissedHeartbeats = 2;
  
      const server = process.env.VUE_APP_BASE_API.split('//')[1]
      socket = new WebSocket(`ws:${server}/ws/log/${engineId}?token=${getToken()}`);
      console.log(socket);

      socket.onopen = function (event) {
        console.log("Connection opened");
        missedHeartbeats = 0;
        // 开始心跳
        _this.interval = setInterval(function () {
          if (missedHeartbeats >= maxMissedHeartbeats) {
            console.log("Missed too many heartbeats, closing connection");
            socket.close();
            return;
          }
          socket.send("ping");
          missedHeartbeats++;
        }, heartbeatInterval);
      };

      socket.onmessage = function (event) {
        console.log("Message received: " + event.data);
        if (event.data === "pong") {
          missedHeartbeats = 0;
        } else{
          _this.logArray.push(event.data)
        }
        // 处理服务器响应的消息
      };

      socket.onclose = function (event) {
        console.log(
          "Connection closed, attempting to reconnect in " +
            reconnectInterval +
            "ms"
        );
        _this.timeout = setTimeout(this.connect, reconnectInterval);
      };

      socket.onerror = function (error) {
        console.log("Error occurred: " + JSON.stringify(error));
        // 处理连接错误的情况
      };
      this.socket = socket;
    },
    load() {
      if(this.showIndex < this.logArray.length) {
        this.showIndex += 10;
        console.log(this.showIndex);
        console.log('触发')
      }
    },
  },
};
</script>
<style scoped lang="scss">
.log-container {
  height: 500px;
  overflow-x: hidden;
  overflow-y: auto; 
  background: #efefef;
  border-radius: 6px;
  padding: 20px;
  .log-item {
    line-height: 30px;
  }
}
</style>
